package com.lemurian.bankdata.bean;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.lemurian.bankdata.bean.base.BaseDaoHibernate;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.entity.Category;

@Repository
public class CategoryDAO extends BaseDaoHibernate<Category>{
	
	private BankDataLogger log = BankDataLogger.getLogger(CategoryDAO.class.getName());

	@Override
	public Category load(int id){
		Category entity = null;
		try {
			Criteria criteria = getSession().createCriteria(Category.class);
			
			criteria.setCacheable(Boolean.TRUE);
			
			criteria.createCriteria("parent", "parent", Criteria.LEFT_JOIN)
				.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
				.setCacheRegion(Category.class.getName());
			
			criteria.add(Restrictions.eq("id", id));
			
			entity = (Category) criteria.uniqueResult();
			
		} catch(Exception exception){
			getSession().getTransaction().rollback();
		}
		return entity;
	}
	
	@SuppressWarnings("unchecked")
	public List<Category> getParents(int parentId) {
		List<Category> parents = null;
		try {
			Criteria criteria = getSession().createCriteria(Category.class);
			
			criteria.add(Restrictions.eq("parent.id", parentId));
			
			parents = criteria.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return parents;
	}
}